package com.ckd.flyingtrip.fragment;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.activity.CarDetailActivity;
import com.ckd.flyingtrip.activity.GoumaiActivity;
import com.ckd.flyingtrip.adapter.BuycarAdapter;
import com.ckd.flyingtrip.adapter.CarentalAdapter;
import com.ckd.flyingtrip.adapter.PopWinAdapter1;
import com.ckd.flyingtrip.adapter.PopWinAdapter2;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.javabean.BuycarAreaBean;
import com.ckd.flyingtrip.javabean.BuycarBean;
import com.ckd.flyingtrip.javabean.BuycarShopBean;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.VolleyErrorUtils;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CarentalFragment extends Fragment {

    @BindView(R.id.fragment_carental_linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.fragment_carental_smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.fragment_carental_recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.fragment_carental_no)
    TextView no;

    private PopupWindow popupWindow;
    private List<BuycarAreaBean.DataBean> dataBeans = new ArrayList<>();
    private PopWinAdapter1 popWinAdapter1;
    private List<BuycarShopBean.DataBean> dataBeanList = new ArrayList<>();
    private PopWinAdapter2 popWinAdapter2;

    private int page = 1;
    private CarentalAdapter adapter;
    private List<BuycarBean.DataBean.ListBean> listBeans = new ArrayList<>();

    private String siteNum = "";

    private boolean aBoolean = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_carental, null);

        ButterKnife.bind(this, view);

        initView();
        initData();
        initListener();

        return view;
    }

    private void initListener() {
        adapter.setOnItemClickListener(new CarentalAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                Intent inten = new Intent(getActivity(), GoumaiActivity.class);
                Intent inten = new Intent(getActivity(), CarDetailActivity.class);
                inten.putExtra("id", listBeans.get(position).getBicycleId());
                startActivity(inten);
            }
        });

        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                if (aBoolean)
                    initBtn();
                else
                    initList();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                smartRefreshLayout.setEnableLoadMore(true);
                page = 1;
                listBeans.clear();
                if (aBoolean)
                    initBtn();
                else
                    initList();
            }
        });
    }

    private void initData() {
        initArea();
        initList();
    }

    private void initList() {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.getallbicycleinfo, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i("租车列表", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        BuycarBean bean = new Gson().fromJson(s, BuycarBean.class);
                        if (smartRefreshLayout != null)
                            smartRefreshLayout.setEnableLoadMore(bean.getData().isHasNextPage());
                        listBeans.addAll(bean.getData().getList());
                        if (adapter != null)
                            adapter.notifyDataSetChanged();
                        if (smartRefreshLayout != null) {
                            smartRefreshLayout.finishLoadMore();
                            smartRefreshLayout.finishRefresh();
                        }
                        if (listBeans.size() == 0) {
                            recyclerView.setVisibility(View.GONE);
                            no.setVisibility(View.VISIBLE);
                        } else {
                            recyclerView.setVisibility(View.VISIBLE);
                            no.setVisibility(View.GONE);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                VolleyErrorUtils.checkError(volleyError);
                if (smartRefreshLayout != null) {
                    smartRefreshLayout.finishLoadMore();
                    smartRefreshLayout.finishRefresh();
                }
                recyclerView.setVisibility(View.VISIBLE);
                no.setVisibility(View.GONE);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("userArea", Constants.CITYID);
                    json_url.put("page", page);
                    json_url.put("row", 10);
                    json_url.put("usedType", 0);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));

                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(getActivity()).addToRequestQueue(request);
    }

    private void initArea() {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.getareaid, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i("地市区域", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        BuycarAreaBean bean = new Gson().fromJson(s, BuycarAreaBean.class);
                        dataBeans.clear();
                        dataBeans.addAll(bean.getData());
                        if (popWinAdapter1 != null)
                            popWinAdapter1.notifyDataSetChanged();
                        if (dataBeans.size() != 0)
                            initShop(dataBeans.get(0).getAreaCode());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("地市区域", "" + volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("userArea", Constants.CITYID);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));

                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(getActivity()).addToRequestQueue(request);
    }

    private void initShop(String areaCode) {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.getbusinessbyareacode, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i("地市区域商家", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        BuycarShopBean bean = new Gson().fromJson(s, BuycarShopBean.class);
                        dataBeanList.clear();
                        dataBeanList.addAll(bean.getData());
                        if (popWinAdapter2 != null)
                            popWinAdapter2.notifyDataSetChanged();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("地市区域商家", "" + volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("areaCode", areaCode);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));

                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(getActivity()).addToRequestQueue(request);
    }

    private void initView() {

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new CarentalAdapter(getActivity(), listBeans);
        recyclerView.setAdapter(adapter);

        initPopWin();
    }

    private void initPopWin() {
        View view = getLayoutInflater().inflate(R.layout.popwin_fragment_buycar_area, null);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        RecyclerView recyclerView1 = view.findViewById(R.id.popwin_fragment_buycar_area_recyclerView1);
        recyclerView1.setLayoutManager(new LinearLayoutManager(getActivity()));
        popWinAdapter1 = new PopWinAdapter1(getActivity(), dataBeans);
        recyclerView1.setAdapter(popWinAdapter1);
        popWinAdapter1.setOnItemClickListener(new PopWinAdapter1.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                initShop(dataBeans.get(position).getAreaCode());
                popWinAdapter1.setAnInt(position);
                popWinAdapter1.notifyDataSetChanged();
                if (popWinAdapter2 != null) {
                    siteNum = "";
                    popWinAdapter2.setAnInt(-1);
                    popWinAdapter2.notifyDataSetChanged();
                }
            }
        });

        RecyclerView recyclerView2 = view.findViewById(R.id.popwin_fragment_buycar_area_recyclerView2);
        recyclerView2.setLayoutManager(new LinearLayoutManager(getActivity()));
        popWinAdapter2 = new PopWinAdapter2(getActivity(), dataBeanList);
        recyclerView2.setAdapter(popWinAdapter2);
        popWinAdapter2.setOnItemClickListener(new PopWinAdapter2.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                siteNum = dataBeanList.get(position).getSiteNum();
                popWinAdapter2.setAnInt(position);
                popWinAdapter2.notifyDataSetChanged();
            }
        });

        TextView btn = view.findViewById(R.id.popwin_fragment_buycar_area_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (siteNum.equals("")) {
                    Toast.makeText(getActivity(), "请先选择商家！", Toast.LENGTH_SHORT).show();
                    return;
                }
                aBoolean = true;
                page = 1;
                listBeans.clear();
                initBtn();
                popupWindow.dismiss();
            }
        });

        LinearLayout ll = view.findViewById(R.id.popwin_fragment_buycar_area_ll);
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        View v = view.findViewById(R.id.popwin_fragment_buycar_area_view);
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    private void initBtn() {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.MAICHEXINXI, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i("商家租车列表", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        BuycarBean bean = new Gson().fromJson(s, BuycarBean.class);
                        if (smartRefreshLayout != null)
                            smartRefreshLayout.setEnableLoadMore(bean.getData().isHasNextPage());
                        listBeans.addAll(bean.getData().getList());
                        if (adapter != null)
                            adapter.notifyDataSetChanged();
                        if (smartRefreshLayout != null) {
                            smartRefreshLayout.finishLoadMore();
                            smartRefreshLayout.finishRefresh();
                        }
                        if (listBeans.size() == 0) {
                            recyclerView.setVisibility(View.GONE);
                            no.setVisibility(View.VISIBLE);
                        } else {
                            recyclerView.setVisibility(View.VISIBLE);
                            no.setVisibility(View.GONE);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("商家租车列表", "" + volleyError);
                if (smartRefreshLayout != null) {
                    smartRefreshLayout.finishLoadMore();
                    smartRefreshLayout.finishRefresh();
                }
                recyclerView.setVisibility(View.VISIBLE);
                no.setVisibility(View.GONE);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("cityId", Constants.CITYID);
                    json_url.put("carType", 0);
                    json_url.put("siteNum", siteNum);
                    json_url.put("page", page);
                    json_url.put("row", 10);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));

                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(getActivity()).addToRequestQueue(request);
    }

    @OnClick(R.id.fragment_carental_area)
    public void onViewClicked() {
        popupWindow.showAsDropDown(linearLayout);
    }


}
